package CarRentalSystem.loginAndRegister;
import CarRentalSystem.JDBCUtils.*;
import java.sql.SQLException;
import java.util.InputMismatchException;
import java.util.Scanner;
import CarRentalSystem.RentMgrSys.RentMgrSys;
import CarRentalSystem.menuMsg.*;

public class Register {
    public static boolean isRepeat(int newAccount){
        String sqlSearchAccount = "select account from usersinfo where account="+newAccount;
        try {
            RentMgrSys.rs = RentMgrSys.stmt.executeQuery(sqlSearchAccount);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if(RentMgrSys.rs.next()){
                if(RentMgrSys.rs.getInt("account") == newAccount){
                    System.out.println("您输入的账号已经被注册了，请换一个账号吧\n");
                    return false;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return true;
    }



    /*
    * 注册程序
    * */
    public static void beginRegister(){
        int newAccount = 0;
        String newPasswords="";
        double money=0.0;
        int whichIdentify=0;
        Scanner in = new Scanner(System.in);

        menuMsg.registerLead();
        menuMsg.registerAccountLead();
        try {
            newAccount = in.nextInt();
        }catch (InputMismatchException e){
            System.out.println("\n账号应当为整数！且不超过10位！请重新注册！\n");
            //e.printStackTrace();
            beginRegister();
        }
        String c = in.nextLine();

        if (!isRepeat(newAccount)){
            beginRegister();
        }

        menuMsg.registerPasswordsLead();
        try {
            newPasswords = in.nextLine();
            if(newPasswords.length() > 10){
                throw new InputMismatchException();
            }
        }catch (InputMismatchException e){
            System.out.println("\n密码应当为字符,且不能超过10位！请重新注册！\n");
            beginRegister();
        }

        menuMsg.registerSetMoney();
        money = in.nextDouble();

        menuMsg.resgisterChooseIdentify();
        whichIdentify = in.nextInt();

        RentMgrSys.usersNums++;
        String identify = whichIdentify==1?"VIP":"ordinary";
        money = whichIdentify==1?money-1000:money;
        String sql = jdbcUtilsByAdmin.sqlAddCostomer(RentMgrSys.usersNums,newAccount, newPasswords, identify, money);

        int count=0;
        try {
            count = RentMgrSys.stmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(count==1){
            System.out.println("注册成功！");
            if (whichIdentify == 1){
                menuMsg.becomeVIP();
            }
            menuMsg.registerSuccess(newAccount, newPasswords);
        }else{
            System.out.println("发生错误，注册失败，请联系管理员处理。");
        }
    }
}
